﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WR.BL.BE;
using WR.BL.BCC;
using System.Net;
using System.Text;
using System.Net.Mail;
using Microsoft.Reporting.WebForms;
using System.IO;

namespace WR.UI.MobWebApp
{
    public partial class send : System.Web.UI.Page
    {
        private UserBE _objUsr;

        private void checkLogin()
        {
            lblErrorMsg.InnerHtml = string.Empty;
            _objUsr = (UserBE)Session["UserBE"];
            if (_objUsr == null)
            {
                Response.Redirect("login.aspx");
            }
        }

        private static string getParamValueStatic(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        //private void generarReporte(string pNro, SalesOrderBE objSO)
        //{
        //    dsOferta ds = new dsOferta();
        //    DocImprBE doc = new DocImprBE();
        //    doc = SalesOrderBC.getInstance(Session.SessionID).find(pNro);
        //    //----------------------------------------------------------------
        //    System.Collections.Generic.List<DetailBE> lst = objSO.Detalle;
        //    //System.Collections.Generic.List<DetalleBE> lst = doc.Detalle;
        //    dsOferta.dtDetalleDataTable dtDet = new dsOferta.dtDetalleDataTable();
        //    //decimal totalDet = 0;//RGF 20111031
        //    decimal totalCab = 0;//RGF 20111031
        //    decimal descuentoTotal = 0;//RGF 20111102

        //    //foreach (DetalleBE itm in lst)
        //    foreach (DetailBE itm in lst)
        //    {
        //        DataRow dr = dtDet.NewRow();
        //        dr["CodMat"] = Int64.Parse(itm.Material.Codigo).ToString();
        //        //dr["CodMat"] = Int64.Parse(itm.CodMat).ToString();
        //        dr["Material"] = itm.Material.Descripcion;
        //        //dr["Material"] = itm.Material;
        //        dr["Precio"] = itm.Material.Precio;//RGF 20111102
        //        //dr["Precio"] = itm.Precio;
        //        dr["Cant"] = itm.Cant;
        //        dr["Total"] = itm.ImporteTotal;//RGF 20111102
        //        //dr["Total"] = itm.Total;
        //        //totalDet = decimal.Round(itm.Precio * itm.Cant,2);//RGF 20111031
        //        //totalDet = (decimal)string.Format("{0:0,0.00}", itm.Precio * itm.Cant);//RGF 20111031
        //        totalCab = totalCab + itm.ImporteTotal;//RGF 20111102
        //        //dr["Total"] = itm.TotalSinDescuento;//RGF 20111031
        //        descuentoTotal = descuentoTotal + itm.DescuentoTotal;//RGF 20111102
        //        dr["NroPedido"] = pNro;
        //        dtDet.Rows.Add(dr);
        //    }

        //    dsOferta.dtCabeceraDataTable dtcab = new dsOferta.dtCabeceraDataTable();
        //    DataRow drcab = dtcab.NewRow();
        //    drcab["Atencion"] = doc.Cabecera.Atencion;
        //    drcab["Cliente"] = doc.Cabecera.Cliente;
        //    drcab["Fax"] = doc.Cabecera.Fax;
        //    drcab["Fecha"] = doc.Cabecera.Fecha;
        //    drcab["FPago"] = doc.Cabecera.FPago;
        //    drcab["Hora"] = doc.Cabecera.Hora;
        //    drcab["Moneda"] = doc.Cabecera.Moneda;
        //    drcab["NroPedido"] = doc.Cabecera.NroPedido;
        //    drcab["RUC"] = doc.Cabecera.RUC;
        //    drcab["Telf"] = doc.Cabecera.Telf;
        //    drcab["TipoCambio"] = doc.Cabecera.TipoCambio;
        //    drcab["Total"] = totalCab;//RGF 20111102
        //    //drcab["Total"] = doc.Cabecera.Total;
        //    //decimal promocion = doc.Cabecera.Total - totalCab;//RGF 20111031
        //    drcab["TotalBruto"] = doc.Cabecera.Total + descuentoTotal;
        //    //if (promocion > 500)
        //    //{
        //    //    drcab["PromocionVisible"] = false;
        //    //}
        //    //else
        //    //{
        //    //    drcab["PromocionVisible"] = true;
        //    //}
        //    //drcab["Promocion"] = promocion;//RGF 20111031
        //    drcab["Promocion"] = descuentoTotal;//RGF 20111102
        //    drcab["Usuario"] = doc.Cabecera.Usuario;
        //    //string str = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, "/img/logo.jpg");
        //    //drcab["Imagen"] = str; //getParamValueStatic("RutaLogoImpr");
        //    //drcab["Imagen"] = getParamValueStatic("RutaLogoImpr"); //RGF 20111102
        //    dtcab.Rows.Add(drcab);
        //    ReportDataSource rptDataSource1 = new ReportDataSource("dsOferta_dtCabecera", dtcab);
        //    //----------------------------------------------------------------
        //    ReportDataSource rptDataSource = new ReportDataSource("dsOferta_dtDetalle", dtDet);
        //    ReportViewer rv = new ReportViewer();
        //    this.ReportViewer1.LocalReport.DataSources.Clear();
        //    this.ReportViewer1.LocalReport.DataSources.Add(rptDataSource1);
        //    this.ReportViewer1.LocalReport.DataSources.Add(rptDataSource);
        //    this.ReportViewer1.LocalReport.ReportPath = Server.MapPath("reportDoc.rdlc");
        //    this.ReportViewer1.LocalReport.EnableExternalImages = true; 
        //    this.ReportViewer1.LocalReport.Refresh(); 
        //    //_________________________
        //    //paso a PDF
        //    //Export to PDF
        //    string mimeType;
        //    string encoding;
        //    string fileNameExtension;
        //    string[] streams;
        //    Microsoft.Reporting.WebForms.Warning[] warnings;

        //    byte[] pdfContent = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);

        //    string rutaServ = "";// "/WR.UI.MobWebApp/img/pdf/BarcodeReport.pdf";
        //    rutaServ = @"\img\pdf\" + pNro + ".pdf"; //rutaServ.Replace("/", ((char)92).ToString());
        //    rutaServ = Server.MapPath(@"~" + (char)92 + rutaServ );
        //    //string SaveLocation = Server.MapPath(@"~" + (char)92 + rutaServ );

        //    FileStream fs = new FileStream(rutaServ, FileMode.Create, FileAccess.ReadWrite);
        //    fs.Write(pdfContent, 0, pdfContent.Length);
            
        //    fs.Close();
        //    //Return PDF
        //    //this.Response.Clear();
        //    //this.Response.ContentType = "application/pdf";
        //    //this.Response.AddHeader("Content-disposition", @"attachment; filename=/img/pdf/BarcodeReport.pdf");
        //    //this.Response.BinaryWrite(pdfContent);
        //    //this.Response.End();
        //}
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.checkLogin();
                if (!Page.IsPostBack)
                {
                    string pNumDoc = Request.QueryString["nd"];
                    if (!string.IsNullOrEmpty(pNumDoc))
                    {
                        lblDoc.InnerHtml = "Enviar documento: " + pNumDoc;
                        Session["NumDoc"] = pNumDoc;
                    }
                    else
                    {
                        throw new Exception("Operación inválida.");
                    }
                }
            }
            catch (Exception ex)
            {
                lblErrorMsg.InnerHtml = ex.Message;
            }
        }

        protected void lnkSend_Click(object o, EventArgs e)
        {
            string pCorreo = string.Empty;
            pCorreo = txtCorreo.Value.Trim();
            try
            {
                if (string.IsNullOrEmpty(pCorreo))
                {
                    throw new Exception("Falta especificar Correo");
                }
                //---
                string pNumDoc = (string)Session["NumDoc"];
                if (!string.IsNullOrEmpty(pNumDoc))
                {
                    SalesOrderBE objSO;
                    string retVal = SalesOrderBC.getInstance(Session.SessionID).read(pNumDoc, out objSO);
                    //generarReporte(pNumDoc,objSO);
                    if (objSO != null)
                    {
                        //Enviar por correo
                        string correo = SalesOrderBC.getInstance(Session.SessionID).sendCorreo(pCorreo, pNumDoc, objSO.ClaseDocT, objSO.ClaseDoc);
                        if (string.IsNullOrEmpty(correo))
                        {
                            lblOkMsg.InnerHtml = "Mensaje enviado.";
                            //--mtejada---------------------------------------------------------------
                        }
                        else
                        {
                            lblOkMsg.InnerHtml = correo.ToString();
                        }
                    }
                    else
                    {
                        throw new Exception("No se encontró el documento.");
                    }
                }
                else
                {
                    throw new Exception("Operación inválida.");
                }
            }
            catch(Exception ex)
            {
                lblErrorMsg.InnerHtml = ex.Message;
            }
        }

        //private bool sendMail(string pCorreo, string pNumDoc, string pClaseDoc, string pTipoDoc)
        //{
        //    string mailFrom = string.Empty, nameFrom = string.Empty;
        //    string smptHost = string.Empty, smtpPort = string.Empty, smtpTout = string.Empty;
        //    string smptUser = string.Empty, smtpPswd = string.Empty;
        //    string mailSep = string.Empty;
        //    try
        //    {
        //        mailFrom = ConfigurationManager.AppSettings["MAIL_FROM"];
        //        nameFrom = ConfigurationManager.AppSettings["NAME_FROM"];

        //        smptHost = ConfigurationManager.AppSettings["SMTP_HOST"];
        //        smtpPort = ConfigurationManager.AppSettings["SMTP_PORT"];
        //        smtpTout = ConfigurationManager.AppSettings["SMTP_TOUT"];
        //        smptUser = ConfigurationManager.AppSettings["SMTP_USER"];
        //        smtpPswd = ConfigurationManager.AppSettings["SMTP_PSWD"];
        //    }
        //    catch { throw new Exception("Error: Falta ingresar parámetros de configuración."); }

        //    System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage();
        //    correo.From = new MailAddress(mailFrom, nameFrom);
        //    correo.To.Add(pCorreo);
        //    correo.Subject = pClaseDoc + ": " + pNumDoc;

        //    //string pUrl = Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "/");
        //    //string pImgSrc = pUrl + "img/logo.jpg";
        //    //string pCssSrc = pUrl + "css/style.css";
        //    //pUrl += "print.aspx?nd=" + pNumDoc;
        //    //correo.Body = this.getHTMLCode(pUrl);
        //    //correo.Body = correo.Body.Replace("img/logo.jpg", pImgSrc);
        //    //correo.Body = correo.Body.Replace("css/style.css", pCssSrc);
        //    correo.Body += "Saludos:\n\n";
        //    correo.Body += "Adjunto se encuentra el documento " + pClaseDoc + " número: " + pNumDoc + "\n\n";
        //    correo.Body += "Atentamente,\n";
        //    correo.Body += "Maestro Perú\n";
        //    correo.BodyEncoding = Encoding.UTF8;

        //    string rutaServ = "";
        //    rutaServ = @"\img\pdf\" + pNumDoc + ".pdf"; 
        //    rutaServ = Server.MapPath(@"~" + (char)92 + rutaServ);
        //    Attachment Attach = new Attachment(rutaServ);
        //    correo.Attachments.Add(Attach);
        //    correo.IsBodyHtml = false;
        //    correo.Priority = System.Net.Mail.MailPriority.Normal;

        //    SmtpClient smtp = new SmtpClient();
        //    smtp.Host = smptHost;// "127.0.0.1";
        //    smtp.Port = Convert.ToInt16(smtpPort); //25;
        //    smtp.Timeout = Convert.ToInt32(smtpTout); //36000;
        //    if (!string.IsNullOrEmpty(smptUser) && !string.IsNullOrEmpty(smtpPswd))
        //    {
        //        smtp.Credentials = new System.Net.NetworkCredential(smptUser, smtpPswd);
        //    }
        //    try
        //    {
        //        smtp.Send(correo);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        lblErrorMsg.InnerHtml = ex.InnerException.Message;
        //        if (string.IsNullOrEmpty(lblErrorMsg.InnerHtml))
        //        {
        //            lblErrorMsg.InnerHtml = ex.Message;
        //        }
        //        return false;
        //    }
        //    finally
        //    {
        //        correo.Dispose();
        //        System.IO.FileInfo fi = new System.IO.FileInfo(rutaServ);
        //    }
        //}

        //private string getHTMLCode(string pURL)
        //{
        //    string retVal = string.Empty;
        //    // We'll use WebClient class for reading HTML of web page
        //    WebClient wc = new WebClient();

        //    // Read web page HTML to byte array
        //    Byte[] PageHTMLBytes;
        //    if (!string.IsNullOrEmpty(pURL))
        //    {
        //        PageHTMLBytes = wc.DownloadData(pURL);
        //        // Convert result from byte array to string
        //        // and display it in TextBox txtPageHTML
        //        UTF8Encoding oUTF8 = new UTF8Encoding();
        //        retVal = oUTF8.GetString(PageHTMLBytes);
        //    }
        //    return retVal;
        //}
    }
}
